package com.example.administrator.caigou51.widget.wheel;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.administrator.caigou51.R;
import com.example.administrator.caigou51.bean.CategoryBean;
import com.example.administrator.caigou51.bean.RegionBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2015/9/25.
 */
public class SelectAreaPopupWindow extends PopupWindow implements View.OnClickListener, OnWheelChangedListener {
    private RegionBean regionBean;
    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, Map<String, String>> mCitisZipcodeDatasMap = new HashMap<String, Map<String, String>>();


    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();
    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName = "";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode = "";

    private View mMenuView;
    private Activity context;


    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private TextView cancel, complete;
    private InterFaceGetData getData;

    public SelectAreaPopupWindow(Activity context, RegionBean regionBean, InterFaceGetData getData) {
        super(context);
        this.regionBean = regionBean;
        this.context = context;
        this.getData = getData;
        init();
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.contorl_select_area, null);
        mViewProvince = (WheelView) mMenuView.findViewById(R.id.id_province);
        mViewCity = (WheelView) mMenuView.findViewById(R.id.id_city);
        mViewDistrict = (WheelView) mMenuView.findViewById(R.id.id_district);
        cancel = (TextView) mMenuView.findViewById(R.id.cancel);
        complete = (TextView) mMenuView.findViewById(R.id.complete);
        cancel.setOnClickListener(this);
        this.setContentView(mMenuView);
        this.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        this.setAnimationStyle(R.style.AnimBottom);
        ColorDrawable dw = new ColorDrawable(0xb00000);
        this.setBackgroundDrawable(dw);
        mMenuView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = mMenuView.findViewById(R.id.pop_layout).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });
        complete.setOnClickListener(this);
        setUpListener();
        setUpData();
    }



    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
        // 添加onclick事件
    }

    private void setUpData() {
        init();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(context, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            if (mDistrictDatasMap != null && mZipcodeDatasMap != null &&mCitisZipcodeDatasMap!=null) {
                if (mDistrictDatasMap.get(mCurrentCityName) != null) {
                    mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
                    mCurrentZipCode = mCitisZipcodeDatasMap.get(mCurrentCityName).get(mCurrentDistrictName);
                } else {
                    mCurrentDistrictName = null;
                    mCurrentZipCode = null;
                }
            }
        }
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(context, areas));
        mViewDistrict.setCurrentItem(0);
        if (mDistrictDatasMap != null && mZipcodeDatasMap != null &&mCitisZipcodeDatasMap!=null) {
            if (mDistrictDatasMap.get(mCurrentCityName) != null) {
                mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[0];
                mCurrentZipCode = mCitisZipcodeDatasMap.get(mCurrentCityName).get(mCurrentDistrictName);
            } else {
                mCurrentDistrictName = null;
                mCurrentZipCode = null;
            }
        }
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(context, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    void init() {
        if (regionBean != null) {
            mCurrentProviceName = regionBean.getData().get(0).getRegion_name();
            List<RegionBean.DataEntity.CityEntity> cityList = regionBean.getData().get(0).getCity();

            if (cityList != null && !cityList.isEmpty()) {
                mCurrentCityName = cityList.get(0).getRegion_name();
                List<RegionBean.DataEntity.CityEntity.AreaEntity> districtList = cityList.get(0).getArea();
                mCurrentDistrictName = districtList.get(0).getRegion_name();
                mCurrentZipCode = districtList.get(0).getRegion_id();
            }
        }
        //*/
        mProvinceDatas = new String[regionBean.getData().size()];
        for (int i = 0; i < regionBean.getData().size(); i++) {
            // 遍历所有省的数据
            mProvinceDatas[i] = regionBean.getData().get(i).getRegion_name();
            List<RegionBean.DataEntity.CityEntity> cityList = regionBean.getData().get(i).getCity();
            String[] cityNames = new String[cityList.size()];
            for (int j = 0; j < cityList.size(); j++) {
                // 遍历省下面的所有市的数据
                cityNames[j] = cityList.get(j).getRegion_name();
                List<RegionBean.DataEntity.CityEntity.AreaEntity> districtList = cityList.get(j).getArea();
                if (districtList != null) {
                    Map<String, String> mZipcodeDatasMap = new HashMap<>();
                    String[] distrinctNameArray = new String[districtList.size()];
                    RegionBean.DataEntity.CityEntity.AreaEntity[] distrinctArray = new RegionBean.DataEntity.CityEntity.AreaEntity[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        RegionBean.DataEntity.CityEntity.AreaEntity districtModel = new RegionBean.DataEntity.CityEntity.AreaEntity
                                (districtList.get(k).getRegion_id(), districtList.get(k).getRegion_name());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getRegion_name(), districtList.get(k).getRegion_id());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getRegion_name();
                    }
                    mCitisZipcodeDatasMap.put(cityNames[j],mZipcodeDatasMap);
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                } else {
                    Log.i("this_is_city", cityList.get(j).getRegion_name());
                }
            }
            // 省-市的数据，保存到mCitisDatasMap
            mCitisDatasMap.put(regionBean.getData().get(i).getRegion_name(), cityNames);
        }
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        super.showAtLocation(parent, gravity, x, y);
        WindowManager.LayoutParams params = context.getWindow().getAttributes();
        params.alpha = 0.7f;
        context.getWindow().setAttributes(params);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        WindowManager.LayoutParams params = context.getWindow().getAttributes();
        params.alpha = 1.0f;
        context.getWindow().setAttributes(params);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cancel:
                this.dismiss();
                break;
            case R.id.complete:
                getData.getData(mCurrentProviceName, mCurrentCityName, mCurrentDistrictName, mCurrentZipCode);
                this.dismiss();
                break;
        }
    }

    public interface InterFaceGetData{
        public void getData(String ProviceName, String CityName, String DistrictName, String DistrictName_id);
    }
}